<template>
  <div class="fileManage">
    <div class="searchDiv">
      <Form :model="searchItem" :label-width="80">
        <Row :gutter="10">
          <Col span="6">
            <FormItem label="电站">
              <Select v-model="searchItem.powerStation" clearable filterable @on-change="getHd">
                <Option
                  v-for="(item, index) in powerStationList"
                  :value="item"
                  :key="index"
                >{{ item }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="HD编号">
              <Select
                v-model="searchItem.hdNumber"
                clearable
                filterable
                :disabled="HBnumberList.length == 0"
                @on-change="getJz"
              >
                <Option v-for="(item, index) in HBnumberList" :value="item" :key="index">{{ item }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="机组编号">
              <Select
                v-model="searchItem.aircrewNumber"
                clearable
                filterable
                :disabled="JZnumberList.length == 0"
              >
                <Option v-for="(item, index) in JZnumberList" :value="item" :key="index">{{ item }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="标题">
              <Input v-model="searchItem.title" placeholder="请输入"></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="文件分类">
              <Select v-model="searchItem.type"
                  filterable
                  remote
                  :remote-method="FileType"
                  :loading="loading4"
                >
                  <Option v-for="(item, index) in FileTypeList" :value="item.displayName" :key="index">{{item.displayName}}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="上传人">
              <Input v-model="searchItem.uploadUserName" placeholder="请输入"></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="上传日期">
              <DatePicker
                type="date"
                @on-change="time2"
                format="yyyy-MM-dd HH:mm:ss"
                v-model="searchItem.uploadDate"
                placeholder="Select date"
                style="width: 100%"
              ></DatePicker>
            </FormItem>
          </Col>
          <Col span="6">
            <Button type="primary" class="marRight" @click="searchItem.pageNo=1;search()">查询</Button>
            <Button type="success" class="marRight" @click="add">上传文件</Button>
            <Button type="primary" @click="downBtn">导出Excel</Button>
          </Col>
        </Row>
      </Form>
    </div>
    <Table border :columns="columns" :loading="loading" :data="tableData" ></Table>
    <Page show-total :total="total" show-elevator :page-size='searchItem.pageSize' :current="searchItem.pageNo" @on-change='pageChange'  style="margin:20px auto;text-align:center"/>
    <!-- 新增弹窗开始 -->
    <Modal :mask-closable="false" v-model="modal1" :title="title1" width="800" >
           <Form :model="formItem" :label-width="80">
             <Row :gutter="10" class="xzjz">
                  <Col span="24">
                    <FormItem label="标题：">
                      <Input v-model="formItem.title" :maxlength="20" placeholder="请输入"></Input>
                    </FormItem>
                  </Col>
                  <Col span="24">
                    <FormItem label="简介：">
                      <Input type="textarea" v-model="formItem.content" :maxlength="50" placeholder="请输入"></Input>
                    </FormItem>
                  </Col>
                  <Col span="24">
                    <FormItem label="文件链接：">
                      <Input v-model="formItem.fileUrl" :maxlength="100" placeholder="请输入"></Input>
                    </FormItem>
                  </Col>
                   <Col span="12">
                    <FormItem label="文件分类：">
                     <Select v-model="formItem.type" filterable clearable>
                          <Option v-for="(item, index) in FileTypeList" :value="item.displayName" :key="index">{{item.displayName}}</Option>
                      </Select>
                    </FormItem>
                  </Col>
                 <Col span="12">
                    <FormItem :model="formItem" label="电站：">
                        <Select v-model="formItem.powerStation" clearable filterable @on-change="getHd">
                        <Option v-for="(item, index) in powerStationList" :value="item" :key="index">{{item}}</Option>
                    </Select>
                    </FormItem>
                  </Col>
                  <Col span="12">
                    <FormItem label="HD编号：">
                     <Select v-model="formItem.hdNumber" clearable filterable :disabled="HBnumberList.length==0" @on-change="getJz">
                        <Option v-for="(item, index) in HBnumberList" :value="item" :key="index">{{item}}</Option>
                    </Select>
                    </FormItem>
                  </Col>
                  <Col span="12">
                    <FormItem label="机组编号：">
                        <Select v-model="formItem.aircrewNumber" clearable filterable :disabled="JZnumberList.length==0">
                          <Option v-for="(item, index) in JZnumberList" :value="item" :key="index">{{item}}</Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span="12">
                    <FormItem label="上传人：">
                       {{formItem.uploadUserName}}
                    </FormItem>
                  </Col>
                  <Col span="12">
                    <FormItem label="上传时间：">
                       <DatePicker
                        type="date"
                        @on-change="time"
                        format="yyyy-MM-dd HH:mm:ss"
                        v-model="formItem.uploadDate"
                        placeholder="Select date"
                        style="width: 100%"
                      ></DatePicker>
                    </FormItem>
                  </Col>
                  <Col span="24">
                    <FormItem label="附件：">
                      <Upload
                        ref="upload"
                          :show-upload-list="false"
                          :headers='fileheader'
                          :on-success='fileSuccess'
                          :action="apihost+'/admin-api/admins/upload/uploadFile'">
                          <Button icon="ios-cloud-upload-outline">上传文件</Button>
                      </Upload>
                      <ul class="upList" v-if="uploadList.length>0">
                          <li v-for="(item,index) in uploadList">
                            <span style="float:left;width:330px;overflow:hidden;">{{item.substring(item.lastIndexOf('/')+1)}}</span>
                            <Button size="small"  @click="xiazai(item)" type="primary">下载文件</Button>
                            <Button size="small"  @click="fileRemove(index)" type="error">删除</Button>
                          </li>
                      </ul>
                      <!-- <div v-if="formItem.url!=''">
                           <span style="">{{formItem.url.substring(formItem.url.lastIndexOf('/')+1)}}</span>
                          <Button size="small" style="margin-left:30px;margin-right:10px;"  @click="down" type="primary">下载文件</Button>
                          <Button size="small"  @click="formItem.url=''" type="error">删除</Button>
                      </div> -->
                    </FormItem>
                  </Col>
             </Row>
           </Form>
           <div slot="footer">
               <Button @click="modal1=false">取消</Button>
              <Button type="primary" :loading="btnClick" @click="ok">确定</Button>
          </div>
    </Modal>
    <Modal :mask-closable="false" v-model="modal2" width="360" class-name="vertical-center-modal" @on-ok="remove(delID)">
        <p slot="header" style="color:#f60;text-align:center">
            <Icon type="ios-information-circle"></Icon>
            <span>确认删除</span>
        </p>
        <div style="text-align:center">
            <p>确认删除此数据么？</p>
        </div>
    </Modal>
    <!-- 新增弹窗结束 -->
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { getAllEqu } from "@/api/select";
import {
  getSelectOption,
  AddFile,
  SearchList,
  DelFile,
  UpDateFile,downExcel
} from '@/api/fileManage'
import { getToken } from '@/libs/util'
import { log } from 'util'

export default {
  data () {
    return {
      btnClick:false,
      uploadList:[],
      loading:true,
      delID: 0,
      modal2: false,
      modal1: false,
      total: '',
      title1: '新增机组文件',
      loading1: false, // 文件类型加载框
      powerStationList: '',
      loading2: false, // 文件类型加载框
      HBnumberList: '',
      loading3: false, // 文件类型加载框
      JZnumberList: '',
      loading4: false,
      FileTypeList: '',
      fileheader: {
        Authorization: 'Bearer ' + (getToken() ? getToken() : '')
      },
      searchItem: {
        title: '',
        type: '',
        powerStation: '',
        hdNumber: '',
        aircrewNumber: '',
        uploadUserName: '',
        uploadDate: '',
        pageNo: 1,
        pageSize: 10
      },
      allEquList: [],
      allEquList2: [],
      formItem: {
        title: '',
        content: '',
        type: '',
        powerStation: '',
        hdNumber: '',
        aircrewNumber: '',
        uploadDate: '',
        uploadUserId: '',
        uploadUserName: '',
        fileUrl:'',
        url: '',
        id: ''
      },
      columns: [
        {
          type: 'index',
          width: 60,
          title: '序号',
          align: 'center',
          fixed: 'left'
        },
        {
          title: '标题',
          key: 'title',
          width:250
        },
        {
          title: '简介',
          key: 'content',
          width:250
        },
        {
          title: '文件分类',
          key: 'type',
          width:100
        },
        {
          title: '文件链接',
          key: 'fileUrl',
          width:250,
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'text',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      window.open(params.row.fileUrl)
                    }
                  }
                },
                params.row.fileUrl
              )
            ])
          }
        },
        {
          title: '电站',
          key: 'powerStation',
          width:150
        },
        {
          title: 'HD编号',
          key: 'hdNumber',
          width:100
        },
        {
          title: '机组编号',
          key: 'aircrewNumber',
          width:100
        },
        {
          title: '上传人',
          key: 'uploadUserName',
          width:80
        },
        {
          title: '上传时间',
          key: 'uploadDate',
          width:150
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          align: 'center',
          fixed: 'right',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.edit(JSON.stringify(params));
                    }
                  }
                },
                '编辑'
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.openDel(params.row.id)
                    }
                  }
                },
                '删除'
              )
            ])
          }
        }
      ],
      tableData: []
    }
  },
  created () {
    this.search()
  },
  methods: {
    downBtn(){
      downExcel(this.searchItem).then(res => {
         const blob = new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;'});

        const ie = navigator.userAgent.match(/MSIE\s([\d.]+)/),
            ie11 = navigator.userAgent.match(/Trident\/7.0/) && navigator.userAgent.match(/rv:11/),
            ieEDGE = navigator.userAgent.match(/Edge/g),
            ieVer = (ie ? ie[1] : (ie11 ? 11 : (ieEDGE ? 12 : -1)));
        console.log('ie:' + ie);
        console.log('ieVer:' + ieVer);
        if (ie && ieVer < 10) {
            this.message.error('No blobs on IE<10');
            return;
        }
        if (ieVer > -1) {
            window.navigator.msSaveBlob(blob, '文件管理.xlsx');
        } else {
            const url = window.URL.createObjectURL(blob);
            let link = document.createElement('a');
            link.setAttribute('href', url);
            link.setAttribute('download', '文件管理.xlsx');
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        // const blob = new Blob([res]);//处理文档流
        //   const fileName = '文件管理.xlsx';
        //   const elink = document.createElement('a');
        //   elink.download = fileName;
        //   elink.style.display = 'none';
        //   elink.href = URL.createObjectURL(blob);
        //   document.body.appendChild(elink);
        //   elink.click();
        //   URL.revokeObjectURL(elink.href); // 释放URL 对象
        //   document.body.removeChild(elink);
      })
    },
    down(){
     // window.open(this.formItem.url)

    },
    openDel (id) {
      this.modal2 = true
      this.delID = id
      // this.remove(params.index);
    },
    pageChange (e) {
      this.searchItem.pageNo = e
      console.log(this.searchItem.pageNo, '页码')
      this.search()
    },
    time (e) {
      this.formItem.uploadDate = e
    },
    time2 (e) {
      this.searchItem.uploadDate = e
    },
     timeFormat (time) {
       if(time instanceof Date==false){
        return time
      }
                const dateTime = new Date(time)
                const year = dateTime.getFullYear()
                const month = this.addZero(dateTime.getMonth() + 1)
                const date = this.addZero(dateTime.getDate())
                const hour = this.addZero(dateTime.getHours())
                const minute = this.addZero(dateTime.getMinutes())
                const second = this.addZero(dateTime.getSeconds())
                return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second
            },
            addZero (v) {
                return v < 10 ? '0' + v : v
            },
    // 获取电站类型列表
    // powerStation () {
    //   getSelectOption(
    //     {
    //       code: 'dianzhan'
    //     }
    //   ).then(res => {
    //     this.powerStationList = res.data
    //   }).catch(err => {
    //     console.error('err>' + JSON.stringify(err))
    //   })
    // },
    // HBnumber () {
    //   getSelectOption(
    //     {
    //       code: 'hd_code'
    //     }
    //   ).then(res => {
    //     this.HBnumberList = res.data
    //   }).catch(err => {
    //     console.error('err>' + JSON.stringify(err))
    //   })
    // },
    // JZnumber () {
    //   getSelectOption(
    //     {
    //       code: 'jizu_code'
    //     }
    //   ).then(res => {
    //     this.JZnumberList = res.data
    //   }).catch(err => {
    //     console.error('err>' + JSON.stringify(err))
    //   })
    // },
    FileType () {
      getSelectOption(
        {
          code: 'fileType'
        }
      ).then(res => {
        console.log(res)
        this.FileTypeList = res.data
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
      })
    },
    fileRemove(index){
      this.uploadList.splice(index,1)
      this.formItem.url = this.uploadList.join(',')
    },
    fileSuccess (response, file, fileList) {
      // let dataArry=[];
      // for(let i=0;i<fileList.length;i++){
      //   if(fileList[i].response.data){
      //     this.uploadList.push(fileList[i].response.data)
      //   }
      // }
      this.uploadList=this.uploadList.concat(response.data);
      this.formItem.url = this.uploadList.join(',')
      this.$Message.info('报告上传成功！')
    },
    xiazai(src){
      // var oPop = window.open("/fadianAdmin/img/logo.bb0e801d.png", "", "width=100, height=100, top=100, left=100");
      //   for (; oPop.document.readyState != "complete";) {
      //       if (oPop.document.readyState == "complete") break;
      //   }
      //   oPop.document.execCommand("xiazai");
      //   oPop.close();
      //let src="http://119.3.183.253:18083/admin-api/accessPath/WX20200310-142849@2x.png.重命名"
        var eleLink = document.createElement('a');
        eleLink.download = src.substring(src.lastIndexOf('/')+1);
        eleLink.style.display = 'none';
        eleLink.href = src;
        document.body.appendChild(eleLink);
        eleLink.click();
        document.body.removeChild(eleLink);
    },
    remove (id) {
      let obj = {
        id: id
      }
      DelFile(obj).then(res => {
        if (res.code == 0) {
          this.$Message.info('删除成功')
          this.searchItem.pageNo=1
          this.search()
        } else {
          this.$Message.info(res.message)
        }
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
        this.loading3 = false
      })
    },
    search () {
      console.log('开始查询')
      console.log(this.searchItem)
      SearchList(this.searchItem).then(res => {
        console.log(res)
        this.tableData = res.data.list
        this.total = res.data.total
        this.loading=false
        if (res.code == 0) {
        } else {
          this.$Message.info(res.message)
        }
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
        this.loading3 = false
      })
    },
    add () {
      // this.formItem.uploadUserName = this.$store.state.user.userName
      // this.formItem.uploadUserId = this.$store.state.user.userId
      this.formItem= {
        title: '',
        content: '',
        type: '',
        powerStation: '',
        hdNumber: '',
        aircrewNumber: '',
        uploadDate:  new Date(),
        uploadUserId: localStorage.getItem('recordUserId'),
        uploadUserName: localStorage.getItem('recordUserName'),
        fileUrl:'',
        url: '',
        id: ''
      }
      this.$refs.upload.clearFiles();
      this.title1 = '新增机组文件';
      this.uploadList=[];
      this.modal1 = true
    },
    edit (params) {
      this.title1 = '编辑机组文件'
      this.formItem = JSON.parse(params).row
      this.modal1 = true;
      this.allEquList2 = this.allEquList.filter(item => item.powerStation == this.formItem.powerStation);
      let arr2 = this.allEquList2.map(function(item) {
        return item.hdNumber;
      });
      this.HBnumberList = [...new Set(arr2)];

      let arr3 = this.allEquList2.filter(item => item.hdNumber == this.formItem.hdNumber);
      let arr4 = arr3.map(function(item) {
        return item.aircrewNumber;
      });
      this.JZnumberList = [...new Set(arr4)];
      if(this.formItem.url!=null&&this.formItem.url!=''){
        this.uploadList=this.formItem.url.split(',')
      }else{
        this.uploadList=[]
      }
    },
    ok () {
            this.btnClick=true;
      if (this.title1 == '新增机组文件') {
        this.formItem.uploadDate=this.timeFormat(this.formItem.uploadDate);
        AddFile(this.formItem).then(res => {
          console.log(res)
          if (res.code == 0) {
            this.$Message.info('新增成功')
            this.search()
            this.modal1=false;
            this.btnClick=false;
          } else {
            this.$Message.info(res.message)
            this.btnClick=false;
          }
        }).catch(err => {
          console.error('err>' + JSON.stringify(err))
          this.loading3 = false
        })
      }
      if (this.title1 == '编辑机组文件') {
        delete this.formItem._index;
      delete this.formItem._rowKey;
      this.formItem.uploadDate=this.timeFormat(this.formItem.uploadDate);
        UpDateFile(this.formItem).then(res => {
          console.log(res)
          if (res.code == 0) {
            this.$Message.info('修改成功')
            this.search()
            this.modal1=false;
            this.btnClick=false;
          } else {
            this.$Message.info(res.message)
            this.btnClick=false;
          }
        }).catch(err => {
          console.error('err>' + JSON.stringify(err))
        })
      }
    },
    getAllEqument() {
      getAllEqu(null).then(res => {
        this.allEquList = res.data;
        let arr = res.data.map(function(item) {
          return item.powerStation;
        });
        this.powerStationList = [...new Set(arr)];
      });
    },
    getHd(e) {
      this.JZnumberList = [];
      this.allEquList2 = this.allEquList.filter(item => item.powerStation == e);
      let arr2 = this.allEquList2.map(function(item) {
        return item.hdNumber;
      });
      this.HBnumberList = [...new Set(arr2)];
    },
    getJz(e) {
      let arr = this.allEquList2.filter(item => item.hdNumber == e);
      let arr2 = arr.map(function(item) {
        return item.aircrewNumber;
      });
      this.JZnumberList = [...new Set(arr2)];
    }
  },
  mounted () {
    this.getAllEqument();
    this.FileType()
  }
}
</script>

<style lang="less">
.upList li {
    border-bottom:1px solid #eaeaea;
    height:40px;
    line-height:40px;
    padding:0px;
    margin:0px;
    overflow: hidden;
    list-style: none;
    .ivu-btn {
      float:right;
      margin-left:10px;
      margin-top:7px;
    }
  }
.fileManage {
  background: #fff;
  height: 100%;
  padding: 15px;
  font-size: 14px;
  .searchDiv {
    .marRight {
      margin-right: 15px;
    }
  }
  .ivu-form-item {
    margin-bottom: 15px;
  }
}
.baseTitle {
    font-weight: bold;
    font-size:16px;
    margin-bottom:10px;
  }
 .xzjz  {
   .ivu-form-item {
    margin-bottom: 10px;
  }
 }
</style>
